import { setCartData, getCartData, removeCartData } from '@/utils/storage'
import { addCart } from '@/api/cart'
export default {
  namespaced: true, // 打开命名空间
  state: () => ({

    cartData: [] // 购物车数据

  }),

  mutations: {

    setCart (state, obj) {
      state.cartData = obj
      setCartData(obj)
    },
    getCart (state) {
      getCartData() // 获取
    },
    clearCart (state) {
      removeCartData() // 调用删除方法
    },
    // 数组去重
    addItem (state, item) {
      if (!state.cartData.some(i => i.id === item.id)) {
        state.cartData.push(item)

        setCartData(state.cartData)
      }
    }

  },
  actions: {
    // 保存购物车数据
    async addCartDada (context, data) {
      console.log(data)

      context.commit('addItem', data) // 添加数据
      console.log(context.state, 'context')

      const res = await addCart(context.state.cartData)

      return res
    }
  },
  getters: {
    cartDatas: state => state.cartData // 通过getter暴露数据

  }

}
